﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using MDCAdminTool.Controls;

namespace MDCAdminTool.Commands
{
    public abstract class AsyncCommandBindingBase : CommandBinding
    {
        private BackgroundWorker bw;
        private AsyncProgressBar prg;

        protected AsyncCommandBindingBase()
        {
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.DoWork += bw_DoWork;
            bw.RunWorkerCompleted += bw_RunWorkerCompleted;

            prg = Application.Current.Properties["PowerShellProgressBar"] as AsyncProgressBar;

            CanExecute += OnCanExecute;
            Executed   += OnCoreExecuted;
        }

        void bw_RunWorkerCompleted( object sender , RunWorkerCompletedEventArgs e )
        {
            if ( prg != null )
                prg.Stop();
        }
        void bw_DoWork( object sender , DoWorkEventArgs e )
        {
            OnExecuted( sender , e.Argument as ExecutedRoutedEventArgs ); 
        }

        protected void OnCoreExecuted( object sender , ExecutedRoutedEventArgs e )
        {
            if( bw.IsBusy ) return;

            bw.RunWorkerAsync( e );
            
            if( prg == null )
                prg = Application.Current.Properties["PowerShellProgressBar"] as AsyncProgressBar;

            if( prg != null )
                prg.Start();
        }
        
        protected virtual void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
        protected abstract void OnExecuted( object sender , ExecutedRoutedEventArgs e );
    }
}